package com.bdqn.t350.controller;


import com.bdqn.t350.pojo.Page;
import com.bdqn.t350.pojo.SysUser;
import com.bdqn.t350.service.SysUserService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    SysUserService sysUserService;

    @GetMapping("/userListPage")
    public String userListPage(String userName,
                               Integer userRole,
                               @RequestParam(defaultValue = "1") Integer pageIndex,
                               Model model) {
        Page page = new Page();
        //设置当前页
        page.setCurrentPage(pageIndex);

        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setUserRole(userRole);
        List<SysUser> list = sysUserService.getListPageBiz(page, sysUser);
        //获得总记录数
        int count = sysUserService.getCountPageBiz(sysUser);
        page.setTotalRecord(count);
        page.setList(list);

        model.addAttribute("page", page);
        model.addAttribute("userName", userName);
        model.addAttribute("userRole", userRole);
        return "user/listPage";
    }

    @RequestMapping("/toAdd")
    public String toAdd() {
        return "user/add";
    }

    @RequestMapping("/add")
    public String add(SysUser sysUser, HttpServletRequest request) {
        HttpSession session = request.getSession();
        SysUser sessionSysUser = (SysUser) session.getAttribute("sysUser");
        if (sessionSysUser == null) {
            //return "redirect:/login";
            throw new RuntimeException("会话已经过期");
        } else {
            sysUser.setCreatedBy(sessionSysUser.getCreatedBy());
            sysUser.setCreationDate(new Date());
            int count = sysUserService.addService(sysUser);
            if (count < 1) {
                throw new RuntimeException("添加失败,请重新登录");
            }
            return "redirect:/user/userListPage";
        }
    }

    //声明一个局部异常，当出现异常就会进入该方法
//    @ExceptionHandler(value = {RuntimeException.class})
//    public String handlerException(RuntimeException e, HttpServletRequest request) {
//        request.setAttribute("e", e);
//        return "login";
//    }

}
